<template>
  <div
    class="child"
    style="padding: 20px 30px"
  >
    <el-row>
      <el-col :span="18">
        <el-button
          type="success"
          @click="add(1)"
        >添加</el-button>
        <el-button
          type="primary"
          @click="del()"
        >删除</el-button>
      </el-col>
      <el-col :span="6">
        <div class="flex">
          <el-input
            v-model="formInline.search"
            placeholder="请输入内容"
            clearable
          />
          <i
            class="el-icon-search"
            @click="search"
          />
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="title"
          label="标题"
        />
        <el-table-column
          prop="brief"
          label="简介"
        />
        <el-table-column label="是否在首页展示" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.indexType"
              :active-value="1"
              :inactive-value="0"
              @change="changeActive(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div class="btnList">
              <el-button
                type="text"
                @click="edit(scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                @click="del(scope.row)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- *************对话框开始************* -->
    <el-dialog
      :title="typeState ? '添加首页直播设置' : '编辑首页直播设置'"
      :visible.sync="addFormDialog"
      width="650px"
      center
      :close-on-click-modal="false"
    >
      <!-- 新增直播视频 -->
      <div>
        <el-form
          ref="ruleForm"
          :model="addForm"
          label-width="140px"
          :rules="typeRules"
        >
          <el-form-item
            label="分类"
            prop="cereLiveType"
          >
            <el-select
              v-model="addForm.cereLiveType"
              :disabled="fromInputDisabled"
              placeholder="请选择分类"
            >
              <el-option
                v-for="(item, index) in typeData"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="标题"
            prop="title"
          >
            <el-input
              v-model="addForm.title"
              :disabled="fromInputDisabled"
              placeholder="请输入标题"
            />
          </el-form-item>
          <el-form-item
            label="封面"
            prop="feedsImg"
          >
            <el-upload
              :disabled="fromInputDisabled"
              class="avatar-uploader"
              :action="action"
              :headers="myHeaders"
              :show-file-list="false"
              :on-success="
                (res) => {
                  handleAvatarSuccess(res, 'feedsImg');
                }
              "
            >
              <img
                v-if="addForm.feedsImg"
                :src="addForm.feedsImg"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              />
            </el-upload>
            <el-input
              v-model="addForm.feedsImg"
              :disabled="fromInputDisabled"
              style="margin-top: 20px"
              placeholder="请输入图片地址"
            />
            <span class="tips">请上传图片或输入图片地址</span>
          </el-form-item>
          <el-form-item label="计划直播开始时间" prop="startTime">
            <el-date-picker
              v-model="addForm.startTime"
              type="datetime"
              style="width: 370px"
              :disabled="isDisabled"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="计划直播结束时间" prop="endTime">
            <el-date-picker
              v-model="addForm.endTime"
              type="datetime"
              style="width: 370px"
              :disabled="isDisabled"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="直播方式">
            <el-radio-group
              v-model="addForm.liveType"
              :disabled="fromInputDisabled"
            >
              <el-radio :label="2">OBS推流</el-radio>
              <el-radio :label="3">拉流</el-radio>
              <el-radio :label="4">视频</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <template
            v-if="
              addForm.liveType == 2 &&
              (addForm.pushSecret == '' || addForm.pushAddress == '')
            "
          > -->
          <!-- <el-form-item>
              <el-button
                :loading="createOBSlinkLoading"
                @click="handleCreateObsLink"
                >生成OBS推流地址</el-button
              >
            </el-form-item> -->
          <!-- </template> -->
          <template v-if="addForm.liveType == 2 && (addForm.pushSecret !== '' || addForm.pushAddress !== '')">
            <el-form-item
              label="推流链接"
              prop="pushSecret"
            >
              <el-input :value="addForm.pushAddress" />
            </el-form-item>
            <el-form-item
              label="推流密钥"
              prop="pushAddress"
            >
              <el-input :value="addForm.pushSecret" />
            </el-form-item>
          </template>
          <el-form-item
            v-if="addForm.liveType == 3"
            label="拉流地址"
            prop="thirdPullUrl"
          >
            <el-input
              v-model="addForm.thirdPullUrl"
              placeholder="请输入拉流地址"
            />
          </el-form-item>
          <el-form-item
            v-if="addForm.liveType == 4"
            label="回流视频地址"
            prop="recordUrl"
          >
            <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="myHeaders"
              :show-file-list="false"
              accept=".mp4"
              :on-success="
                (res) => {
                  handleAvatarSuccess(res, 'recordUrl');
                }
              "
            >
              <div
                v-if="addForm.recordUrl"
                style="height: 200px; width: 300px"
              >
                <TcPlayerVue
                  style="height: 100%; width: 100%"
                  :src="addForm.recordUrl"
                />
              </div>

              <!-- <video v-if="addForm.recordUrl" style="height:500px;" :src="addForm.recordUrl" class="avatar" width="320" height="240" controls>
                <source :src="addForm.recordUrl" type="video/*">
              </video> -->
              <i
                v-else
                class="el-icon-upload avatar-uploader-icon"
              />
            </el-upload>
            <el-input
              v-model="addForm.recordUrl"
              style="margin-top: 20px"
              placeholder="请输入视频地址"
            />
            <span class="tips">请上传视频或输入视频地址</span>
          </el-form-item>
          <el-form-item
            label="备注"
            prop="brief"
          >
            <el-input
              v-model="addForm.brief"
              :disabled="fromInputDisabled"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleFormCancel">取 消</el-button>
        <el-button
          :disabled="fromInputDisabled"
          type="primary"
          @click="addForm_enter('ruleForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { uploadUrl, token } from '@/utils/request'
import TcPlayerVue from './TcPlayer.vue'
import {
  videoList,
  videoAdd,
  videoDelete,
  liveTypeList, liveToggle
} from '@/api/live'

export default {
  components: {
    TcPlayerVue
  },
  data () {
    return {
      action: uploadUrl,
      myHeaders: {
        'Authorization-admin': token
      },
      formInline: {
        serviceType: -1, // -1： 后台上传 0 小程序直播，1：腾讯云直播
        search: '', // 搜索字段
        page: '1', // 当前页
        pageSize: '10' // 每页记录数
      },
      total: 1,
      tableData: [],
      typeData: [],
      currentPage: 1,
      typeState: 1,
      fromInputDisabled: false,
      addForm: {
        id: '',
        title: '',
        cereLiveType: '',
        brief: '',
        feedsImg: '',
        thirdPullUrl: '',
        recordUrl: '',
        liveType: 2,
        pushAddress: '',
        pushSecret: ''
      },
      addFormDialog: false,
      typeRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        cereLiveType: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        feedsImg: [
          { required: true, message: '请上传或输入封面图', trigger: 'blur' }
        ],
        thirdPullUrl: [
          { required: false, message: '请输入拉流地址', trigger: 'blur' }
        ],
        recordUrl: [
          { required: true, message: '请输入回流视频地址', trigger: 'blur' }
        ],
      },
      multipleSelection: [],
      createOBSlinkLoading: false,
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    addFormDialog: function () {
      if (!this.addFormDialog && this.fromInputDisabled) {
        this.fromInputDisabled = false
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getAll(this.formInline)
  },
  // 方法集合
  methods: {
    async changeActive(row) {
      console.log(row.id,'row.id')
      const res = await liveToggle({ id: row.id, indexType: row.indexType })
      if (res.code === '' && row.indexType === 1) {
        this.$message({
          message: '在首页展示',
          type: 'success'
        })
      } else if (res.code === '' && row.indexType === 0) {
        this.$message({
          message: '不在首页展示',
          type: 'success'
        })
      }
      this.getAll(this.formInline)
    },
    // 图片上传回调
    handleAvatarSuccess (response, key) {
      const { url } = response.data
      this.addForm[key] = url
      this.$forceUpdate()
    },
    handleSelectionChange (val) {
      this.multipleSelection = []
      val.map(c => {
        this.multipleSelection.push(c.id)
      })
      //   this.multipleSelection = this.multipleSelection.join(',')
    },
    handleSizeChange (val) {
      this.formInline.pageSize = val
      this.getAll(this.formInline)
    },
    handleCurrentChange (val) {
      this.formInline.page = val
      this.getAll(this.formInline)
    },
    removeTag (index) {
      console.log(index)
    },
    tagChange (index) {
      this.$forceUpdate()
      console.log(index)
    },
    // 查询
    search () {
      this.total = 1
      this.formInline.page = 1
      this.getAll(this.formInline)
    },
    // 新增直播视频
    add (index) {
      this.typeState = 1
      if (index === 1) {
        this.addForm = {
          id: '',
          title: '',
          cereLiveType: '',
          brief: '',
          feedsImg: '',
          thirdPullUrl: '',
          recordUrl: '',
          liveType: 2,
          pushAddress: '',
          pushSecret: ''
        }
        this.addFormDialog = true
      }
    },
    // 确认新增直播视频
    addForm_enter (ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.typeState) {
            console.log(this.addForm)

            videoAdd(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
              }
              if (this.addForm.liveType === 2) {
                this.addForm.pushAddress = res.data.pushAddress
                this.addForm.pushSecret = res.data.pushSecret
                this.fromInputDisabled = true
              } else {
                this.addFormDialog = false
              }
              this.getAll(this.formInline)
            })
          } else {
            videoAdd(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.addFormDialog = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑直播视频
    edit (row) {
      this.typeState = 0
      this.addFormDialog = true
      console.log(row)
      this.addForm = { ...row }
    },
    // 删除直播视频
    async del (row) {
      if (row) {
        const res = await videoDelete({ id: row.id })
        if (res.code === '') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getAll(this.formInline)
      } else if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择数据'
        })
        return
      } else {
        const res = await videoDelete({ ids: this.multipleSelection })
        if (res.code === '') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getAll(this.formInline)
      }
    },
    // 初始化查询所有数据
    async getAll (formInline) {
      const restype = await liveTypeList({
        name: '', // 搜索字段
        page: '1', // 当前页
        pageSize: '1000' // 每页记录数
      })
      this.typeData = restype.data.list
      const res = await videoList(formInline)
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 生成OBS链接和密钥
    handleCreateObsLink () {
      this.createOBSlinkLoading = true
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const pushSecret = 'www.baidu.com/adfdadsfadsfxxx'
          const pushAddress = 'xxxxxxxxxxxxxxx'
          this.addForm.pushSecret = pushSecret
          this.addForm.pushAddress = pushAddress
          this.createOBSlinkLoading = false
          return resolve({
            pushSecret,
            pushAddress
          })
        }, 2000)
      })
    },
    handleFormCancel () {
      this.addFormDialog = false
      // this.fromInputDisabled = false
    }
  }
};
</script>
      <style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
  i {
    font-size: 26px;
    margin-left: 10px;
  }
}
.tableBox {
  padding-top: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 178px;
  height: auto;
  display: block;
}
</style>

